<?php

/**
 * 
 * @version $Id: ContatoController.php 2 2012-05-26 02:24:18Z joaopaulopvillela@gmail.com $
 */
class Default_ContatoController extends Zend_Controller_Action
{
	/**
	 * 
	 * @var Default_Form_Contato
	 */
	protected $_form;
	
	/** 
	 * 
	 * @var Zend_Config_Ini
	 */
	protected $_config;
	
	/**
	 * 
	 * @var Model_Mapper_Contato
	 */
	protected $_mapper;
	
	/**
	 * (non-PHPdoc)
	 * @see Zend_Controller_Action::init()
	 */
	public function init()
	{
		$this->_mapper 	= new Model_Mapper_Contato();
		$this->_config 	= Zend_Registry::get( 'config' );
		$this->_form 	= $this->_getForm( $this->_helper->url('save') );
	}
	
	/**
	 * 
	 * @access 	public
	 * @param 	string $action
	 * @return 	Default_Form_Contato
	 */
	protected function _getForm ( $action )
	{
		$form = new Default_Form_Contato(
			array(
				'action' 	=> $action,
				'method' 	=> Zend_Form::METHOD_POST,
				'id' 		=> 'form-contato',
				'onSubmit'  => 'return contato();'
			)
		);
			
		return $form;
	}
	
	/**
	 * 
	 * @access public
	 * @return void
	 */
	public function indexAction ()
	{
		$this->view->form = $this->_form;
	}
	
	/**
	 *
	 * @access public
	 * @return void
	 */
	public function saveAction ()
	{
		if ( $this->getRequest()->isPost() ) {
			
			if ( $this->_form->isValid($this->getRequest()->getPost()) ) {
				
				$result = array(
					'valid' 	=> $this->_mapper->send($this->_form->getValues()),
					'message' 	=> $this->_mapper->getMessage()->toArray() 
				);
				
			} else {
				
				$message = new App_Message();
				
				$message->addMessage( $this->_config->messages->warning, App_Message::WARNING );
				
				$result = array(
					'valid' 	=> false,
					'message' 	=> $message->toArray(),
					'error' 	=> $this->_form->getMessages() 
				);
				
			}
			
			$this->_helper->json( $result );
			
		}

		$this->_helper->redirector->gotoSimple('index');
	}
}